﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace ChinaClipping.ClippingMaster.MyTools
{
    public class Wrapper
    {

        TripleDESCryptoServiceProvider _tripledes = new TripleDESCryptoServiceProvider();
        SHA1CryptoServiceProvider _sha = new SHA1CryptoServiceProvider();

        private byte[] truncateHash(string key, int length)
        {
            byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
            byte[] hash = _sha.ComputeHash(keyBytes);
            byte[] rtn = new byte[length];
            if (hash.Length <= length)
                hash.CopyTo(rtn, 0);
            else
            {
                for (int i = 0; i < rtn.Length; i++)
                {
                    rtn[i] = hash[i];
                }
            }
            return rtn;
        }

        public Wrapper(string key)
        {
            _tripledes.Key = truncateHash(key, _tripledes.KeySize / 8);
            _tripledes.IV = truncateHash("", _tripledes.BlockSize / 8);
        }

        public string EncryptString(string txt)
        {
            try
            {
                byte[] txtBytes = Encoding.Unicode.GetBytes(txt);
                MemoryStream ms = new MemoryStream();
                CryptoStream encStream = new CryptoStream(ms, _tripledes.CreateEncryptor(), CryptoStreamMode.Write);
                encStream.Write(txtBytes, 0, txtBytes.Length);
                encStream.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch { return ""; };
        }

        public string DecryptString(string txt)
        {
            try
            {
				if (string.IsNullOrEmpty(txt))
					return null;
				else
				{
					byte[] txtBytes = Convert.FromBase64String(txt);
					MemoryStream ms = new MemoryStream();
					CryptoStream encStream = new CryptoStream(ms, _tripledes.CreateDecryptor(), CryptoStreamMode.Write);
					encStream.Write(txtBytes, 0, txtBytes.Length);
					encStream.FlushFinalBlock();
					return Encoding.Unicode.GetString(ms.ToArray());
				}
            }
            catch(Exception ex)
			{
				return "";
			}
        }
    }
}
